/*
 * @Descripttion: 
 * @Author: junhuafly
 * @Date: 2020-03-05 17:04:38
 * @LastEditors: junhuafly
 * @Email: junhuafly@163.com
 * @LastEditTime: 2020-04-15 12:02:16
 */
// pages/mine/home/index.js
import {
  userAPI
} from './../../../api/user'
import {
  returnStatus,
  returnStatusToast,
  UploadFile
} from './../../../utils/index'
var appInst =  getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    showAction: false,
    confirmDel: false,
    customerId: 16,
    infos: {},
    isFollow: false,
    notes: [],
    pageNum: 1,
    requestObj: {},
    bgWallImg: '',
    percentage: 0,
    isProgress: false,
  },
  onQuery() {
    wx.showToast({
      title: '已拉黑，可在设置-黑名单中查看',
      icon: 'none',
      image: '',
      duration: 1500,
      mask: false,
      success: async (result) => {
        const _ = await userAPI.joinBlackUser({
          userId: this.data.customerId
        })
        const res = await returnStatus(_)
        if(res){
          if(res && _.code===200){
            wx.showToast({
              title:_.message,
              duration:800,
              icon:'none'
            })
          }
        }
        this.setData({
          showAction: false
        })
      },
      fail: () => {},
      complete: () => {
        this.setData({
          showAction: false
        })
      }
    });
  },
  onClose(){
        wx.hideToast();
  },
  toDetail({target:{dataset:{id}}}){
    wx.navigateTo({
      url: '/pages/note/detail/index?id='+id,
    })
  },
  async infoAction(){
    this.setData({showAction:true})
  },

  cancelAction(){
    this.setData({showAction:false})
  },
  async joinBlackUser(){
    this.setData({confirmDel:true})
  },
  // 获取图片
  async handleWallImage({
    detail
  }) {
    const {
      file
    } = detail
    const _this = this
    wx.navigateTo({
      url: '/pages/cropper/index',
      events: {
        async cropperSuccess({data}){
          // 执行上传操作
          _this.setData({
            isProgress: true,
            showCropper: false
          })
          setTimeout(() => {
          wx.showLoading({
            title: '正在上传..',
        });
          }, 800);
          const _ = await UploadFile.upload(data, 'OTHER', (progress) => {
            _this.setData({
              percentage: progress,
              isProgress: progress != 100
            })
          })
          if (_) {
            const res = await userAPI.putCustomerInfosBgWall({
              personalBackgroundUrl: _
            })
            if (res) {
              _this.setData({
                bgWallImg: _
              })
            }
          }

        }
      },
      success(res){
        res.eventChannel.emit('propsObj', { data: {
          imagePath:file.path,
          aspectRatio:2.3437
        } })
      }

    })
  },


  // 操作关注取消关注
  async handleCustomerFollow() {
    const _ = await userAPI.handleFollowUser({
      follow: !this.data.isFollow,
      followCustomerId: this.data.customerId
    })
    returnStatusToast(_, () => {
      this.setData({
        isFollow: !this.data.isFollow
      })
    })
  },
  // 获取用户笔记信息
  getData() {
    return new Promise(async (resolve, reject) => {
      const _ = await userAPI.queryCustomerNotes({
        pageNum: this.data.pageNum,
        customerId: this.data.customerId,
        pageSize: 10,
      })
      const res = await returnStatus(_)
      if (res) {
        this.setData({
          notes: [...this.data.notes, ...res.records],
          pageNum: ++this.data.pageNum
        })
        resolve(res.records.length)
      } else {
        reject(false)
      }
    })
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function ({customerId}) {
    this.setData({
      customerId
    })
    
    appInst.setTitle('个人信息')
    
    this.setData({
      requestObj: {
        fetchData: (refresh) => {
          refresh ? this.setData({
            pageNum: 1,
            notes: []
          }) : ''
          return this.getData()
        },
      }
    })
    // 获取个人用户信息
    userAPI.queryCustomerInfos({
      customerId: this.data.customerId
    }).then(async _ => {
      const res = await returnStatus(_)
      if (res) {
        this.setData({
          infos: res,
          bgWallImg: res.personalBackgroundUrl
        })
      }
      userAPI.hasFollowed({
        followCustomerId: this.data.customerId
      }).then(async _ => {
        const isFollow = await returnStatus(_)
        this.setData({
          isFollow: isFollow !== "NOT_FOLLOWED"
        })
      })
      this.getData()
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})